<template>
  <div id="studentScorePage">
    <div style="display: flex; justify-content: space-between">
      <!-- 搜索栏 -->
      <a-form layout="inline" :model="searchParam" @finish="doSearch">
        <a-form-item label="学生姓名">
          <a-input
            v-model:value="searchParam.studentName"
            placeholder="请输入学生姓名"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="课程名称">
          <a-input
            v-model:value="searchParam.courseName"
            placeholder="请输入课程名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="成绩">
          <a-input v-model:value="searchParam.score" placeholder="请输入成绩" allow-clear />
        </a-form-item>
        <a-form-item label="等级">
          <a-select v-model:value="searchParam.gradeLevel" style="width: 120px">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="A">A</a-select-option>
            <a-select-option value="B">B</a-select-option>
            <a-select-option value="C">C</a-select-option>
            <a-select-option value="D">D</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit"> 搜索 </a-button>
        </a-form-item>
      </a-form>
      <a-button type="primary" size="large" @click="showAddModel">新增学生成绩</a-button>
    </div>
    <div style="margin-bottom: 32px"></div>
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH-mm-ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="showUpdateModel(record.id)">修改</a-button>
            <a-button type="primary" danger @click="doDelete(record.id)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>
    <a-modal v-model:open="addModel" title="添加学生成绩" @ok="doAdd">
      <div style="height: 16px"></div>
      <a-form
        :model="formDataAdd"
        name="addStudentScore"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item label="学生姓名" name="studentName">
          <a-auto-complete
            v-model:value="formDataAdd.studentName"
            :options="studentList.map((item) => ({ value: item.studentName, id: item.id }))"
            @change="onStudentChange"
            @select="(value: string, option: MockVal) => onStudentSelect(value, option, 'add')"
            placeholder="请输入学生姓名"
          />
        </a-form-item>
        <a-form-item label="课程名称" name="courseName">
          <a-auto-complete
            v-model:value="formDataAdd.courseName"
            :options="courseList.map((item) => ({ value: item.courseName, id: item.id }))"
            @change="onCourseChange"
            @select="(value: string, option: MockVal) => onCourseSelect(value, option, 'add')"
            placeholder="请输入课程名称"
          />
        </a-form-item>
        <a-form-item label="成绩" name="score">
          <a-input-number v-model:value="formDataAdd.score" :min="0" :max="150" />
        </a-form-item>
<!--        <a-form-item label="等级" name="gradeLevel">-->
<!--          <a-auto-complete-->
<!--            v-model:value="formDataAdd.gradeLevel"-->
<!--            :options="gradeLevelList"-->
<!--            placeholder="请输入等级"-->
<!--          />-->
<!--        </a-form-item>-->
        <a-form-item label="备注信息" name="remarks">
          <a-textarea v-model:value="formDataAdd.remarks" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:open="updateModel" title="更新学生成绩" @ok="doUpdate">
      <div style="height: 16px"></div>
      <a-form
        :model="formDataUpdate"
        name="updateStudentScore"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item label="学生姓名" name="studentName">
          <a-auto-complete
            v-model:value="formDataUpdate.studentName"
            :options="studentList.map((item) => ({ value: item.studentName, id: item.id }))"
            @change="onStudentChange"
            @select="(value: string, option: MockVal) => onStudentSelect(value, option, 'update')"
            placeholder="请输入学生姓名"
          />
        </a-form-item>
        <a-form-item label="课程名称" name="courseName">
          <a-auto-complete
            v-model:value="formDataUpdate.courseName"
            :options="courseList.map((item) => ({ value: item.courseName, id: item.id }))"
            @change="onCourseChange"
            @select="(value: string, option: MockVal) => onCourseSelect(value, option, 'update')"
            placeholder="请输入课程名称"
          />
        </a-form-item>
        <a-form-item label="成绩" name="score">
          <a-input-number v-model:value="formDataUpdate.score" :min="0" :max="150" />
        </a-form-item>
<!--        <a-form-item label="等级" name="gradeLevel">-->
<!--          <a-auto-complete-->
<!--            v-model:value="formDataUpdate.gradeLevel"-->
<!--            :options="gradeLevelList"-->
<!--            placeholder="请输入等级"-->
<!--          />-->
<!--        </a-form-item>-->
        <a-form-item label="备注信息" name="remarks">
          <a-textarea v-model:value="formDataUpdate.remarks" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import {
  addStudentScoreUsingPost,
  deleteStudentScoreUsingPost,
  getStudentScoreByIdUsingGet,
  listStudentScoreByPageUsingPost,
  updateStudentScoreUsingPost,
} from '@/api/studentScoreController.ts'
import { listStudentUsingPost } from '@/api/studentController.ts'
import { listCourseUsingPost } from '@/api/courseController.ts'

const addModel = ref<boolean>(false)
const updateModel = ref<boolean>(false)

interface MockVal {
  value: string
  id: number
}

const columns = [
  {
    title: '学生姓名',
    dataIndex: 'studentName',
  },
  {
    title: '课程名称',
    dataIndex: 'courseName',
  },
  {
    title: '成绩',
    dataIndex: 'score',
  },
  {
    title: '等级',
    dataIndex: 'gradeLevel',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 定义数据
const dataList = ref<API.StudentScore[]>([])
const total = ref(0)

const gradeLevelList = [
  {
    value: 'A',
  },
  {
    value: 'B',
  },
  {
    value: 'C',
  },
  {
    value: 'D',
  },
]

// 搜索条件
const searchParam = reactive<API.StudentScoreQueryRequest>({
  current: 1,
  pageSize: 10,
  studentName: '',
  courseName: '',
  score: undefined,
  gradeLevel: '',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParam.current,
    pageSize: searchParam.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共${total}条`,
  }
})

const doTableChange = (page: any) => {
  searchParam.current = page.current
  searchParam.pageSize = page.pageSize
  fetchData()
}

// 获取数据
const fetchData = async () => {
  const res = await listStudentScoreByPageUsingPost({
    ...searchParam,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}

const studentList = ref<API.Student[]>([])
const fetchStudentList = async () => {
  const res = await listStudentUsingPost({})
  if (res.data.code === 0 && res.data.data) {
    studentList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}
const courseList = ref<API.Course[]>([])
const fetchCourseList = async () => {
  const res = await listCourseUsingPost({})
  if (res.data.code === 0 && res.data.data) {
    courseList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}

// 页面加载时获取数据，请求一次
onMounted(() => {
  fetchData()
  fetchStudentList()
  fetchCourseList()
})

const onStudentChange = async (value: string) => {
  const res = await listStudentUsingPost({
    studentName: value,
  })
  if (res.data.code === 0 && res.data.data) {
    studentList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}
const onStudentSelect = async (value: string, option: MockVal, key: string) => {
  if (key === 'add') {
    formDataAdd.studentId = option.id
  } else {
    formDataUpdate.value.studentId = option.id
  }
}

const onCourseChange = async (value: string) => {
  const res = await listCourseUsingPost({
    courseName: value,
  })
  if (res.data.code === 0 && res.data.data) {
    courseList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}

const onCourseSelect = async (value: string, option: MockVal, key: string) => {
  if (key === 'add') {
    formDataAdd.courseId = option.id
  } else {
    formDataUpdate.value.courseId = option.id
  }
}

const doSearch = () => {
  // 重置页码
  searchParam.current = 1
  fetchData()
}

const doDelete = async (id: number) => {
  if (!id) {
    return
  }
  const res = await deleteStudentScoreUsingPost({ id: id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败')
  }
}

const formDataAdd = reactive<API.StudentScoreAddRequest>({
  studentId: undefined,
  studentName: '',
  courseId: undefined,
  courseName: '',
  score: undefined,
  gradeLevel: '',
  remarks: '',
})
const formDataUpdate = ref<API.StudentScoreUpdateRequest>({
  studentId: undefined,
  studentName: '',
  courseId: undefined,
  courseName: '',
  score: undefined,
  gradeLevel: '',
  remarks: '',
})

const doUpdate = async () => {
  const res = await updateStudentScoreUsingPost({
    ...formDataUpdate.value,
  })
  if (res.data.code === 0 && res.data.data !== null) {
    message.success('更新成功')
    fetchData()
    updateModel.value = false
  } else {
    message.error('更新失败, ' + res.data.message)
  }
}

const doAdd = async () => {
  const res = await addStudentScoreUsingPost({
    ...formDataAdd,
  })
  if (res.data.code === 0 && res.data.data !== null) {
    message.success('添加成功')
    fetchData()
    addModel.value = false
  } else {
    message.error('添加失败, ' + res.data.message)
  }
}

const showAddModel = async () => {
  formDataAdd.studentId = undefined
  formDataAdd.studentName = ''
  formDataAdd.courseId = undefined
  formDataAdd.courseName = ''
  formDataAdd.score = undefined
  formDataAdd.gradeLevel = ''
  formDataAdd.remarks = ''
  fetchStudentList()
  fetchCourseList()
  addModel.value = true
}

const showUpdateModel = async (id: number) => {
  const res = await getStudentScoreByIdUsingGet({ id })
  if (res.data.code === 0 && res.data.data !== null) {
    formDataUpdate.value = {
      ...res.data.data,
    }
  } else {
    message.error('获取数据失败, ' + res.data.message)
  }
  updateModel.value = true
}
</script>

<style scoped></style>
